package ext.generic.part;

import com.ptc.windchill.enterprise.util.PartManagementHelper;
import com.ptc.core.components.beans.ObjectBean;
import com.ptc.core.components.forms.FormProcessingStatus;
import com.ptc.core.components.forms.FormResult;
import com.ptc.core.components.util.FeedbackMessage;
import com.ptc.core.security.slcc.SLCCConstants.object_status;
import com.ptc.core.ui.resources.FeedbackType;
import com.ptc.core.ui.validation.*;
import com.ptc.netmarkets.model.NmOid;
import com.ptc.netmarkets.util.beans.*;
import com.ptc.netmarkets.util.misc.*;
import com.ptc.windchill.enterprise.wip.WIPUtils;
import com.ptc.windchill.uwgm.common.prefs.res.newCadDocPrefsResource;

import java.sql.Timestamp;

import java.util.*;

import org.apache.log4j.Logger;

import wt.access.*;

import wt.doc.WTDocument;
import wt.doc.WTDocumentMaster;

import wt.epm.workspaces.EPMWorkspaceHelper;
import wt.epm.workspaces.EPMWorkspaceManager;

import wt.facade.scm.ScmFacade;

import wt.fc.*;
import wt.fc.collections.*;

import wt.folder.*;

import wt.generic.*;

import wt.identity.DisplayIdentity;
import wt.identity.IdentityFactory;

import wt.inf.container.*;
import wt.inf.library.WTLibrary;

import wt.introspection.LinkInfo;
import wt.introspection.WTIntrospector;

import wt.log4j.LogR;

import wt.org.WTUser;

import wt.part.*;

import wt.pdmlink.PDMLinkProduct;

import wt.pom.Transaction;

import wt.preference.PreferenceHelper;
import wt.preference.PreferenceService2;

import wt.projmgmt.ProjMgmtHelper;
import wt.projmgmt.ProjMgmtService;
import wt.projmgmt.admin.Project2;

import wt.query.ClassAttribute;
import wt.query.QuerySpec;
import wt.query.SearchCondition;

import wt.session.SessionHelper;

import wt.type.ClientTypedUtility;

import wt.util.*;

import wt.vc.sessioniteration.SessionIterationHelper;
import wt.vc.sessioniteration.SessionIterationService;
import wt.vc.struct.StructHelper;
import wt.vc.struct.StructService;
import wt.vc.wip.WorkInProgressHelper;
import wt.vc.wip.WorkInProgressService;

import wt.session.SessionHelper;

import wt.lifecycle.*;

import wt.org.WTPrincipal;

import ext.com.core.CoreUtil;
import ext.tianma.part.PartWorkflowUtil;

/**
 *处理有关零部件关联对象的常用方法
 */
public class GenericPartManagementHelper extends PartManagementHelper
{
    /**
     *创建零部件与文档的关联,是响应JSP页面请求的入口方法
     * @param nmcommandbean
     * @param flag
     * @return
     * @throws WTException
     */
    public static FormResult addRelationDocPart(NmCommandBean nmcommandbean, boolean flag) throws WTException
    {
        WTCollection wtcollection = null;
        WTArrayList wtarraylist = new WTArrayList();
        Vector vector = new Vector();
        FormResult formresult = new FormResult();
        formresult.setStatus(FormProcessingStatus.SUCCESS);
        boolean flag1 = getWcPDMMethodPref();
        ArrayList arraylist = nmcommandbean.getSelected();
        WTDocument wtdocument = (WTDocument) nmcommandbean.getPrimaryOid().getWtRef().getObject();
        if (flag1)
        {
            if (flag)
            {
                WTDocumentMaster wtdocumentmaster = (WTDocumentMaster) wtdocument.getMaster();
                wtarraylist.add(wtdocumentmaster);
            }
            else
            {
                wtarraylist.add(wtdocument);
            }
        }
        else
        {
            if (flag)
            {
                if (PartDocHelper.isReferenceDocument(wtdocument))
                {
                    WTDocumentMaster wtdocumentmaster1 = (WTDocumentMaster) wtdocument.getMaster();
                    wtarraylist.add(wtdocumentmaster1);
                }
            }
            else if (!PartDocHelper.isReferenceDocument(wtdocument))
                wtarraylist.add(wtdocument);
        }

        if (wtarraylist.size() > 0)
        {
            if (arraylist != null && arraylist.size() > 0)
            {
            	/**
            	 * @author xuge_ning
            	 * @reason 文档关联所有视图的部件
            	 */
            	WTArrayList partList = null;
            	NmContext nmcontext0 = (NmContext) arraylist.get(0);
            	Persistable persistable0 = nmcontext0.getTargetOid().getWtRef().getObject();
            	if (persistable0 instanceof WTPart){
            		 
            		WTPart wtpart = (WTPart) persistable0;
            		partList = PartWorkflowUtil.getAllPartViews(wtpart);
            		wtpart = CoreUtil.getWTPartByNumberAndView(wtpart.getNumber(), "Design");
            		partList.add(wtpart);
            		System.out.println("文档关联所有部件：" + partList.toString() + ",partList.size():" + partList.size());
            		for(int i = 0;i<partList.size();i++){
            			wtpart = (WTPart) partList.getPersistable(i);
            			wtcollection = createRelationship(wtarraylist, wtpart, flag, true, false);
            			Iterator iterator = wtcollection.persistableIterator();
            			while (iterator.hasNext())
            	        {
            	            Object obj = iterator.next();
            	            if ((obj instanceof WTPart)) {
            	              vector.add(obj);
            	            }
            	        }
            		}
                }
            	
            	/**
            	 * end
            	 */
                label0:
                for (int i = 0; i < arraylist.size(); i++)
                {
                	NmContext nmcontext = (NmContext)arraylist.get(i);
                    Persistable persistable = nmcontext.getTargetOid().getWtRef().getObject();
                    if ((persistable instanceof WTProductInstance2))
                    {
                      WTProductInstance2 wtproductinstance2 = (WTProductInstance2)persistable;
                      System.out.println("文档关联单个部件" + wtproductinstance2.toString());
                      wtcollection = createRelationship(wtarraylist, wtproductinstance2, flag);
                    }
                    Iterator iterator = wtcollection.persistableIterator();

                    while (iterator.hasNext())
                    {
                      Object obj = iterator.next();
                      if ((obj instanceof WTPart)) {
                        vector.add(obj);
                      }
                    }
                }
            }
            if (vector.size() != 0)
            {
                Locale locale = SessionHelper.getLocale();
                formresult.addFeedbackMessage(getAddFbMsg(FeedbackType.FAILURE, vector, locale));
                formresult.setStatus(FormProcessingStatus.SUCCESS);
            }
        }
        return formresult;
    }

    /**
     *创建零部件与文档的关联
     * @param wtcollection 文档列表
     * @param wtpart
     * @param flag
     * @param flag1
     * @param flag2
     * @return
     * @throws WTException
     */
    public static WTCollection createRelationship(WTCollection wtcollection, WTPart wtpart, boolean flag, boolean flag1, boolean flag2) throws WTException
    {
        WTPrincipal curUser = SessionHelper.manager.getPrincipal();
        SessionHelper.manager.setAdministrator();

        WTArrayList wtarraylist = new WTArrayList();
        Object obj = new WTArrayList();
        boolean flag3 = WIPUtils.enableableObject(wtpart).booleanValue();
        boolean flag4 = WIPUtils.isCheckOutValid(wtpart, "full");
        boolean flag5 = false;
        if (flag3 || flag4)
        {
            if (flag)
                obj = createPartDocReferenceLinks(wtpart, wtcollection);
            else
                obj = createPartDocDescribeLinks(wtpart, wtcollection);
            if (flag1 && flag5)
                if (((WTCollection) (obj)).size() > 0)
                    wtpart = (WTPart) WIPUtils.getCheckInObject(wtpart);
                else
                    wtpart = (WTPart) WIPUtils.getUndoCheckOutObject(wtpart);
        }
        else if (((WTCollection) (obj)).size() == 0)
            wtarraylist.add(wtpart);

        SessionHelper.manager.setPrincipal(curUser.getName());
        return wtarraylist;
    }

    /**
     *创建零部件与参考文档的关联
     * @param wtpart
     * @param wtcollection
     * @return
     * @throws WTException
     */
    public static WTCollection createPartDocReferenceLinks(WTPart wtpart, WTCollection wtcollection) throws WTException
    {
        System.out.println("createPartDocReferenceLinks");
        WTCollection collection = wtcollection;
        Iterator iterator = wtcollection.persistableIterator();
        do
        {
            if (!iterator.hasNext())
                break;
            Object obj = iterator.next();
            if (obj instanceof WTDocumentMaster)
            {
                System.out.println("参考文档关联部件");
                WTPartReferenceLink link = WTPartReferenceLink.newWTPartReferenceLink(wtpart, (WTDocumentMaster) obj);
                PersistenceServerHelper.manager.insert(link);
                //collection.add(link);
            }
        }
        while (true);

        return collection;
    }

    /**
     *创建零部件与普通文档的关联
     * @param wtpart
     * @param wtcollection
     * @return
     * @throws WTException
     */
    public static WTCollection createPartDocDescribeLinks(WTPart wtpart, WTCollection wtcollection) throws WTException
    {
        System.out.println("createPartDocDescribeLinks");
        WTCollection collection = wtcollection;
        Iterator iterator = wtcollection.persistableIterator();
        do
        {
            if (!iterator.hasNext())
                break;
            Object obj = iterator.next();
            if (obj instanceof WTDocument)
            {
                System.out.println("文档关联部件");
                WTPartDescribeLink link = WTPartDescribeLink.newWTPartDescribeLink(wtpart, (WTDocument) obj);
                PersistenceServerHelper.manager.insert(link);
                //collection.add(link);
            }
        }
        while (true);

        return collection;
    }

    /**
     *删除零部件与文档关联;是响应JSP请求的入口方法
     * @param nmcommandbean
     * @param flag
     * @return
     * @throws WTException
     */
    public static FormResult deleteRelationDocPart(NmCommandBean nmcommandbean, boolean flag) throws WTException
    {
        Object obj = new WTArrayList();
        WTArrayList wtarraylist = new WTArrayList();
        Vector vector = new Vector();
        FormResult formresult = new FormResult();
        formresult.setStatus(FormProcessingStatus.SUCCESS);
        boolean flag1 = getWcPDMMethodPref();
        ArrayList arraylist = nmcommandbean.getSelected();
        WTDocument wtdocument = (WTDocument) nmcommandbean.getPrimaryOid().getWtRef().getObject();
        if (flag1)
        {
            if (flag)
            {
                WTDocumentMaster wtdocumentmaster = (WTDocumentMaster) wtdocument.getMaster();
                wtarraylist.add(wtdocumentmaster);
            }
            else
            {
                if (WIPUtils.enableableObject(wtdocument).booleanValue() && !WorkInProgressHelper.isWorkingCopy(wtdocument))
                    wtdocument = (WTDocument) WorkInProgressHelper.service.workingCopyOf(wtdocument);
                wtarraylist.add(wtdocument);
            }
        }
        else if (flag)
        {
            if (PartDocHelper.isReferenceDocument(wtdocument))
            {
                WTDocumentMaster wtdocumentmaster1 = (WTDocumentMaster) wtdocument.getMaster();
                wtarraylist.add(wtdocumentmaster1);
            }
        }
        else if (!PartDocHelper.isReferenceDocument(wtdocument))
        {
            if (WIPUtils.enableableObject(wtdocument).booleanValue() && !WorkInProgressHelper.isWorkingCopy(wtdocument))
                wtdocument = (WTDocument) WorkInProgressHelper.service.workingCopyOf(wtdocument);
            wtarraylist.add(wtdocument);
        }
        if (wtarraylist.size() > 0 && arraylist != null && arraylist.size() > 0)
        {
            label1:
            for (int i = 0; i < arraylist.size(); i++)
            {
                NmContext nmcontext = (NmContext) arraylist.get(i);
                Persistable persistable = nmcontext.getTargetOid().getWtRef().getObject();
                if (persistable instanceof WTPart)
                {
                    //去掉文档和零部件的关联
                    WTPart wtpart = (WTPart) persistable;
                    //obj = deleteRelationship(wtarraylist, wtpart, flag, true, false);
                    wtdocument = (WTDocument) nmcommandbean.getPrimaryOid().getWtRef().getObject();
                    WTPartDescribeLink link = getDescribeLinkBetweenPartAndDoc(wtpart, wtdocument);
                    if (link == null)
                    {
                        WTPartReferenceLink reflink = getReferenceLinkBetweenPartAndDoc(wtpart, wtdocument);
                        if (reflink != null)
                        {
                            PersistenceServerHelper.manager.remove(reflink);
                            System.out.println("删除零部件:" + wtpart.getIdentity() + "和文档" + wtdocument.getIdentity() + "描述关联");
                        }
                    }
                    else
                    {
                        PersistenceServerHelper.manager.remove(link);
                        System.out.println("删除零部件:" + wtpart.getIdentity() + "和文档" + wtdocument.getIdentity() + "参考关联");
                    }
                    obj = wtarraylist;
                }
                else if (persistable instanceof WTProductInstance2)
                {
                    WTProductInstance2 wtproductinstance2 = (WTProductInstance2) persistable;
                    obj = deleteRelationship(wtarraylist, wtproductinstance2, flag, false);
                }
                Iterator iterator = ((WTCollection) (obj)).persistableIterator();
                do
                {
                    if (!iterator.hasNext())
                        continue label1;
                    Object obj1 = iterator.next();
                    if ((obj1 instanceof WTPart) || (obj1 instanceof WTProductInstance2))
                        vector.add(obj1);
                }
                while (true);
            }

        }
        if (vector.size() != 0)
        {
            Locale locale = SessionHelper.getLocale();
            formresult.addFeedbackMessage(getRemoveFbMsg(FeedbackType.FAILURE, vector, locale));
            formresult.setStatus(FormProcessingStatus.SUCCESS);
        }
        return formresult;
    }

    /**
     * 获取零部件与文档的描述类的关联关系（WTPartDescribeLink）
     * @param part 想要获取关联关系的零部件
     * @param document 想要获取关联关系的文档
     * @return 返回关联关系列表，如果零部件或文档不存在，返回空
     * @throws WTException
     * <br><br>
     * <b>getDescribeLinkBetweenPartAndDoc</b>
     * <br><b>Rev:</b> 1.0 - 2006/03/21, kan
     * <br><b>Comment:</b> 根据零部件得到描述的关联关系，然后根据关系得到文档，最后文档进行比较。
     */
    public static WTPartDescribeLink getDescribeLinkBetweenPartAndDoc(WTPart part, WTDocument document) throws WTException
    {
        //用于存放WTPartDescribeLink的连接关系
        Vector docLinkV = new Vector();

        //得到和当前零件关联的文档的描述关系WTPartDescribeLink
        QueryResult qr = WTPartHelper.service.getDescribedByWTDocuments(part, false);
        if (qr != null && qr.hasMoreElements())
        {
            while (qr.hasMoreElements())
            {
                //将对象添加到
                WTObject obj = (WTObject) qr.nextElement();
                docLinkV.addElement(obj);
            }
        }

        //遍历整个关联关系的列表，进行比较
        if ((docLinkV != null) && (docLinkV.size() > 0))
        {
            for (int i = 0; i < docLinkV.size(); i++)
            {
                WTPartDescribeLink describeLink = (WTPartDescribeLink) docLinkV.elementAt(i);
                WTDocument doc = (WTDocument) describeLink.getDescribedBy();
                //比较文档是不是相同，如果相同的话，返回WTPartDescribeLink
                if (PersistenceHelper.isEquivalent(doc, document))
                    return describeLink;
            }
        }
        return null;
    }

    /**
     * 获取零部件与文档的参考类的关联关系（WTPartReferenceLink）
     * @param part 想要获取关联关系的零部件
     * @param document 想要获取关联关系的文档
     * @return 返回关联关系列表，如果零部件或文档不存在，返回空。
     * @throws WTException
     * <br><br>
     * <b>getReferenceLinkBetweenPartAndDoc</b>
     * <br><b>Rev:</b> 1.0 - 2006/03/21, kan
     * <br><b>Comment:</b>
     */
    public static WTPartReferenceLink getReferenceLinkBetweenPartAndDoc(WTPart part, WTDocument document) throws WTException
    {
        //得到document的编码
        String docnumber = document.getNumber();

        //遍历所有的WTPartReferenceLink，根据doc的编码判断是不是需要的link
        QueryResult qr = PersistenceHelper.manager.navigate(part, "references", WTPartReferenceLink.class, false);
        while (qr != null && qr.hasMoreElements())
        {
            //得到link
            WTPartReferenceLink link = (WTPartReferenceLink) qr.nextElement();

            //得到link的docmaster
            WTDocumentMaster docmaster = (WTDocumentMaster) link.getReferences();

            //得到master的number
            String docmasternumber = docmaster.getNumber();

            //判断是不是需要的link,如果相等,返回link
            if (docmasternumber.compareToIgnoreCase(docnumber) == 0)
                return link;
        }
        return null;
    }
}
